package cn.qianxun.meta.common.core.utils.bean;

import org.dozer.DozerBeanMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author fuzhilin
 * @Date 2023/9/18 9:01
 * @Description 通用对象转换
 */
public class GeneralConv {
    /**
     * 对象通用转换
     *
     * @param source           源对象
     * @param destinationClass 目标类
     * @param <T>              T
     * @return 返回得到destinationClass
     */
    public static <T> T conv(Object source, Class<T> destinationClass) {
        if (null == source) {
            return null;
        }
        if(source.getClass().isInstance(destinationClass)){
            return (T)source;
        }
        DozerBeanMapper dozerMapper = new DozerBeanMapper();

        return dozerMapper.map(source, destinationClass);
    }

    /**
     * 集合转换
     *
     * @param sourceList       源集合
     * @param destinationClass 目标类
     * @param <T>              T
     * @return 返回得到destinationClass的集合结果
     */
    public static <T> List<T> convert2List(List<?> sourceList, Class<T> destinationClass) {
        List<T> destinationList = new ArrayList<>();
        sourceList.forEach(source -> {
            if(source.getClass().isInstance(destinationClass)){
                destinationList.add((T)source);
            }else{
                destinationList.add(GeneralConv.conv(source, destinationClass));
            }
        });
        return destinationList;
    }
}
